﻿using ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Models;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
using Common;
using IServices;
using static System.String;

namespace WebApi.Controllers
{
    public class UserController : BaseController
    {
        private readonly JwtHelper _jwtHelper;
        private IUserService _userService;
        public UserController(JwtHelper jwtHelper, IUserService userService)
        {
            _jwtHelper = jwtHelper;
            _userService = userService;
        }
        public IActionResult Index()
        {
            return new ApiResult(1, "hello");
        }

        public IActionResult Info(string token)
        {
            //var token = HttpContext.Request.Headers["token"].FirstOrDefault()?.Split(" ").Last();
            if (IsNullOrEmpty(token))
                return new ApiResult(0, "token missing");

            var validatedToken = _jwtHelper.ValidateJwtToken(token);
            var userID = validatedToken.Claims.FirstOrDefault(m => m.Type == "id");
            var permissionVM = _userService.GetUserPermissionVM(int.Parse(userID.Value));

            return new ApiResult(1, $"hello {permissionVM.Name} ", permissionVM);
        }

        [HttpPost]
        public async Task<IActionResult> Login([FromBody] UserLoginForm form)
        {
            var user = _userService.GetByName(form.Username);
            if (user == null)
                return new ApiResult(0, $"user not exists");

            var token = _jwtHelper.GenerateJwtToken(user);
            return new ApiResult(1, $"hello {form.Username}, your password is {form.Password}", new { token });
        }

    }
}
